import React = require("react");
import { PageProps } from "maishu-chitu-react";
import { DesignView } from "controls/design-view";
import { LocalService } from "services/local-service";
import { pageDatas } from "services/page-datas";
import { SpinerComponent } from "controls/spiner-component";
import { ImageService } from "maishu-services-sdk";
import * as ui from "maishu-ui-toolkit";
import { Categories, Props as CategoriesProps } from "components/categories/component";
import { asyncComponentState } from "common";
import { ItemDialog } from "controls/item-dialog";
import { createService } from "components/common/base-component";
import imageManager from "controls/image-manager";
import { ShoppingService } from "services/shopping";
import { dataSources } from "services/dataSources";
import { PageDataRecord } from "entities";
import { ComponentData } from "maishu-jueying";


interface State {
    pageDataRecord: PageDataRecord,
    status?: "loading" | "complete",
    categories?: ProductCategory[]
}

export default class CategoriesPage extends SpinerComponent<PageProps, State> {
    localService: LocalService;
    imageService: ImageService;
    categoryTable: HTMLElement;
    designView: DesignView;
    categoriesComponent: Categories;
    categoryDialog: CategoryDialog;
    shoppingService: ShoppingService;

    constructor(props) {
        super(props);

        this.localService = this.props.createService(LocalService);
        this.imageService = this.props.createService(ImageService);
        this.shoppingService = this.props.createService(ShoppingService)
    }

    async loadData() {
        let pageDataRecord = await pageDatas.categories();
        return { pageDataRecord };
    }

    categoriesProps(): CategoriesProps {
        let { pageDataRecord, categories } = this.state;
        let categoriesData = pageDataRecord.pageData.children.filter(o => o.type == Categories.name)[0];
        return categoriesData.props as CategoriesProps;
    }

    editItem(category: ProductCategory) {
        this.categoryDialog.show(category, "编辑品类", async (item) => {
            await this.shoppingService.updateCategory(item);
            this.setState({})
        });
    }

    newItem() {
        this.categoryDialog.show({} as ProductCategory, "新增类别", async (item) => {
            let { categories } = this.state;
            await this.shoppingService.addCategory(item);
            categories.push(item);
            this.setState({ categories });
        });
    }

    private designViewRef(e: DesignView) {
        if (this.designView != null || e == null)
            return;

        this.designView = e;
        this.designView.designer.attach(designer => {
            if (designer == null)
                return;


            this.categoriesComponent = designer.findComponetsByTypeName(Categories.name)[0] as Categories;
            asyncComponentState(this.categoriesComponent, this, "categories");
        })
    }

    render() {
        let { pageDataRecord: pageData, categories } = this.state;
        categories = (categories || []).sort((a, b) => {
            return (a.SortNumber || 0) - (b.SortNumber || 0);
        });

        let categoriesProps = this.categoriesProps();
        let { showIcon } = categoriesProps;
        return <DesignView {...this.props}
            ref={e => this.designViewRef(e)}
            {...{ pageDataRecord: pageData, hideEditorPanel: true }}>
            <table className="table table-striped table-bordered table-hover"
                ref={e => this.categoryTable = e || this.categoryTable}>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>名称</th>
                        <th>备注</th>
                        <th>隐藏</th>
                        <th>图片</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {categories.map((o, i) =>
                        <tr key={o.Id || i}>
                            <td>{o.SortNumber}</td>
                            <td>{o.Name}</td>
                            <td>{o.Remark}</td>
                            <td>{o.Hidden}</td>
                            <td style={{ textAlign: 'center' }}>
                                <img src={this.imageService.imageSource(o.ImagePath)} style={{ height: 36 }} />
                            </td>
                            <td style={{ textAlign: 'center' }}>
                                <button className="btn btn-minier btn-info" style={{ marginRight: 4 }}
                                    ref={(e: HTMLButtonElement) => {
                                        if (!e) return;
                                        e.onclick = () => this.editItem(o);
                                    }}>
                                    <i className="icon-pencil"></i>
                                </button>
                                <button className="btn btn-minier btn-danger"
                                    ref={(e: HTMLButtonElement) => {
                                        if (!e) return;
                                        e.onclick = ui.buttonOnClick(async (event) => {
                                            await dataSources.category.delete(o);
                                            categories = categories.filter(c => c.Id != o.Id);
                                            this.setState({ categories });

                                        }, { confirm: `确定要删除类别'${o.Name}'吗?` })
                                    }}>
                                    <i className="icon-trash"></i>
                                </button>
                            </td>
                        </tr>
                    )}
                    {categories.length == 0 ?
                        <tr>
                            <td colSpan={6} className="text-center" style={{ padding: `80px 0 80px 0` }}>
                                暂无数据
                            </td>
                        </tr> : null
                    }
                </tbody>
            </table>
            <div className="well" style={{ display: "inline-block", width: "100%" }}>
                <div className="pull-left" style={{ paddingTop: 4, paddingRight: 10, paddingLeft: 10 }}>
                    显示图标
                    </div>
                <label className="pull-left switch">
                    <input type="checkbox" className="ace ace-switch ace-switch-5"
                        checked={showIcon}
                        onChange={e => {
                            categoriesProps.showIcon = e.target.checked;
                            this.setState({ pageDataRecord: pageData });
                        }} />
                    <span className="lbl middle"></span>
                </label>
                <div className="pull-right">
                    <button className="btn btn-primary" onClick={() => this.newItem()}>
                        <i className="icon-plus" style={{ marginRight: 4 }}></i>
                        添加类别
                        </button>
                </div>
            </div>
            <CategoryDialog showIcon={showIcon} ref={e => this.categoryDialog = e || this.categoryDialog} />
        </DesignView>
    }
}

class CategoryDialog extends ItemDialog<{ showIcon: boolean }, ProductCategory> {
    imageService: ImageService;
    constructor(props) {
        super(props)

        this.imageService = createService(ImageService);
    }
    render() {
        let { showIcon } = this.props;
        let { item } = this.state || {} as this["state"];
        return <div className="form-horizontal">
            <div className="form-group">
                <label className="control-label col-sm-2">序号</label>
                <div className="col-sm-10">
                    <input name="sortNumber" className="form-control"
                        placeholder="商品类别的序号(可空)" value={item.SortNumber || ""}
                        onChange={e => {
                            item.SortNumber = Number.parseInt(e.target.value);
                            this.setState({ item });
                        }} />
                </div>
            </div>
            <div className="form-group">
                <label className="control-label col-sm-2">名称*</label>
                <div className="col-sm-10">
                    <input name="Name" className="form-control"
                        placeholder="商品类别的名称(必填)"
                        value={item.Name || ""}
                        onChange={e => {
                            item.Name = e.target.value;
                            this.setState({ item });
                        }} />
                </div>
            </div>
            <div className="form-group">
                <label className="control-label col-sm-2">备注</label>
                <div className="col-sm-10">
                    <input name="Remark" className="form-control"
                        placeholder="商品类别的备注信息(可空)"
                        value={item.Remark || ""}
                        onChange={e => {
                            item.Remark = e.target.value;
                            this.setState({ item })
                        }} />
                </div>
            </div>
            <div className="form-group" style={{ display: showIcon ? 'block' : 'none' }}>
                <label className="control-label col-sm-2">图片</label>
                <div className="col-sm-10">
                    <div className="well" style={{ margin: 0, padding: 0 }}>
                        <img style={{ width: 100, height: 100 }}
                            src={this.imageService.imageSource(item.ImagePath)} title="点击上传图片"
                            ref={(e) => {
                                if (!e) return;
                                ui.renderImage(e, { imageSize: { width: 100, height: 100 } });
                                e.onclick = () => {
                                    imageManager.show((imageIds) => {
                                        item.ImagePath = imageIds[0];
                                        this.setState(this.state);
                                    })
                                }
                            }} />
                    </div>
                </div>
            </div>
            <div className="form-group">
                <div className="col-sm-offset-2 col-sm-10">
                    <div className="checkbox">
                        <label>
                            <input name="Hidden" type="checkbox"
                                checked={item.Hidden}
                                onChange={(e) => {
                                    item.Hidden = e.target.checked;
                                    this.setState({ item });
                                }} />
                            在前台隐藏该类别
                    </label>
                    </div>
                </div>
            </div>

        </div>
    }
}